<?php

namespace App\Http\Controllers\Manage;

use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use App\Manage;
use Hash;
use Validator;
// 验证码flc/alidayu
use Flc\Alidayu\Client;
use Flc\Alidayu\App;
use Flc\Alidayu\Requests\AlibabaAliqinFcSmsNumSend;
use App\Verifycode;

class ManageController extends Controller
{
    //
    public function login() {
        return view('manage.login');
    }

    /**
     * 验证码
     */
    public function captcha() {
        $builder = new CaptchaBuilder();
        $builder->build($width = 86, $height = 34);
        Session::flash('captcha', $builder->getPhrase());
        header('Content-type:image/jpeg');
        $builder->output($quality = 80);
    }

    /**
     * 管理员登录验证
     */
    public function verify(Request $request) {
/*        $input = $request->only('email', 'password', 'captcha');
        dump($input);
        $results = Manage::all();
        foreach ($results as $result) {
            echo $result->email;
        }*/

        $input = $request->only('email', 'password', 'captcha');
        $callback = null;
        $rule = [
            'email' => 'required|',
            'password' => 'required|min:5',
            'captcha' => 'required|size:5'
        ];
        $message = [
            'email.required' => '邮箱不能为空',
            'password.required' => '密码不能为空',
            'password.min' => '密码长度最少 6 位',
            'captcha.required' => '验证码不能为空',
            'captcha.size' => '验证码长度 5 位'
        ];
        $validator = Validator::make($input, $rule, $message);
        if ($validator->fails()) {
            $callback = [
                'code' => 101,
                'msg' => '数据格式验证失败'
            ];
        } elseif ($input['captcha'] != session('captcha')) {
            $callback = [
                'code' => 102,
                'msg' => '验证码错误'
            ];
        }
        else {
            $result = Manage::select('id', 'role_id', 'password', 'login_number', 'username')
                ->where('email', $input['email'])
                ->where('status', 1)
                ->get();  //->first();
            foreach($result as $result) {
                if ($result && Hash::check($input['password'], $result->password)) {
                    Manage::where('email', $result['email'])
                        ->where('status', 1)
                        ->update([
                            'login_time' => date('Y-m-d H:i:s'),
                            'login_number' => $result['login_number'] + 1,
                            'ip' => $request->getClientIp()
                        ]);
                    $user = [
                        'id' => $result['id'],
                        'role_id' => $result['role_id'],
                        'email' => strtolower($input['email']),
                        'name'=> $result['username']
                    ];
                    session(['user' => $user]);
                    $callback = [
                        'code' => 100,
                        'msg' => '登录成功'
                    ];
                } else {
                    $callback = [
                        'code' => 103,
                        'msg' => '邮箱或密码错误'
                    ];
                }
            }

        }
        return json_encode($callback);
    }

    public function logout() {
        Session::flush();
        return redirect('manage/login');
    }

    // 测试验证短信登录
    public function login1() {
        return view('manage.login1');
    }
    /**
     * 管理员登录验证（验证码）
     */
    public function verifyPhone(Request $request) {
        $callback = null;

        $phone = $request->input('phone');
        $number = rand(1000,9999);
        // 配置
        $config = [
            'app_key' => '23513462',
            'app_secret' => '42daeba85cc68be199ac5c09632c8c3c',
        ];

        $client = new Client(new App($config));
        $req = new AlibabaAliqinFcSmsNumSend;

        $req->setRecNum($phone)
            ->setSmsParam([
                'number' => $number
            ])
            ->setSmsFreeSignName('测试')
            ->setSmsTemplateCode('SMS_35985201');
        $resp = $client->execute($req);
        if($resp->result->err_code == 0) {
            $hasPhone = VerifyCode::wherePhone($phone)->first();
            if($hasPhone) {
                VerifyCode::wherePhone($phone)->update([
                    'code' => $number,
                    'model' => $resp->result->model
                ]);

            }
            else {
                VerifyCode::insert([
                    'model' => $resp->result->model,
                    'phone' => $phone,
                    'code' => $number
                ]);
            }

            $callback = [
                'code' => 103,
                'msg' => '发送成功'
            ];
        }
        else {
            $callback = [
                'code' => 404,
                'msg' => '获取验证码失败'
            ];
        }
        return $callback;

//        print_r($resp);
//        print_r($resp->result->model);

    }

    public function verifyLogin(Request $request) {

        $phone = $request->input('phone');
        $code = $request->input('verify');
        $hasPhone = Verifycode::wherePhone($phone)->first();
        if($hasPhone) {
            $hasCode = Verifycode::whereCode($code)->first();
            if($hasCode) {
                return redirect()->back()->withSuccess('验证成功');
            }
            else {
                return redirect()->back()->withInput()->withErrors('手机号码存在但验证码不存在！');
            }
        }
        else {
            return redirect()->back()->withInput()->withErrors('手机号码不存在！');
        }
    }


}
